/*
 * IwoNew.java
 * 
 * Copyright (c) 2012 Supin P Surendran <supinps@gmail.com>.
 * 
 * This file is part of InventoryMan.
 * 
 * InventoryMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * InventoryMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with InventoryMan.  If not, see <http ://www.gnu.org/licenses/>.
 */

/*
 * IwoNew.java
 *
 * Created on 20 Dec, 2012, 11:17:16 AM
 */

package InventoryMan;

import java.awt.event.ActionEvent;
import java.sql.SQLException;

/**
 *
 * @author Supin P Surendran <supinps@gmail.com>
 */
public class IwoView extends javax.swing.JInternalFrame {

    /** Creates new form IwoView
     * @param conn Connection to the Database
     */
    @SuppressWarnings("static-access")
    public IwoView(java.sql.Connection conn) {
        imConnection=conn;
        print=false;
        comboIwo=new javax.swing.DefaultComboBoxModel();
        TblItemsModel=new javax.swing.table.DefaultTableModel(new Object[]{"Sl No","Product","Quantity","Area","Remarks"}, 0);
        initComponents();
        ac.decorate(CmbIwo);
        TblIwo.setModel(TblItemsModel);
        initCmbIwo();
        initCmbIwoListener();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        DueDate = new org.jdesktop.swingx.JXDatePicker();
        IwoDate = new org.jdesktop.swingx.JXDatePicker();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        TxtDept = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TxtCustomer = new javax.swing.JTextArea();
        CmbIwo = new org.jdesktop.swingx.JXComboBox();
        TxtDespatch = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        TblIwo = new javax.swing.JTable();
        BnOk = new javax.swing.JButton();
        BnCancel = new javax.swing.JButton();

        setTitle("View IWO");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/icon_small.png"))); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Due Date :");

        DueDate.setEditable(false);

        IwoDate.setEditable(false);

        jLabel3.setText("IWO No :");

        jLabel4.setText("IWO Date :");

        jLabel7.setText("TO :");

        TxtDept.setEditable(false);

        jLabel8.setText("Mode of Despatch :");

        jLabel1.setText("Customer :");

        TxtCustomer.setColumns(20);
        TxtCustomer.setEditable(false);
        TxtCustomer.setRows(5);
        jScrollPane1.setViewportView(TxtCustomer);

        CmbIwo.setModel(comboIwo);

        TxtDespatch.setEditable(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(CmbIwo, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
                    .addComponent(IwoDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(DueDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(TxtDept, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                    .addComponent(TxtDespatch, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(61, 61, 61))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(TxtDept, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(28, 28, 28)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(TxtDespatch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel3)
                                        .addComponent(jLabel1)
                                        .addComponent(CmbIwo, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGap(45, 45, 45))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGap(45, 45, 45)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel4)
                                        .addComponent(IwoDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGap(18, 18, 18)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(DueDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)))
                .addContainerGap(35, Short.MAX_VALUE))
        );

        TblIwo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Sl No", "Product", "Quantity", "Area", "Remarks"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        TblIwo.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(TblIwo);

        BnOk.setText("Fetch Items");
        BnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BnOkActionPerformed(evt);
            }
        });

        BnCancel.setText("Cancel");
        BnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 1070, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(BnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(49, 49, 49)
                        .addComponent(BnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(BnCancel)
                    .addComponent(BnOk))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BnOkActionPerformed
        try {
            if(!print) {
                stmt_items=imConnection.createStatement();
                reply_items=stmt_items.executeQuery("SELECT iwo_item.sl_no,item.name,iwo_item.quantity,item.width,item.length,indent_item.remarks " +
                                                    "FROM iwo_item INNER JOIN iwo_entry INNER JOIN indent_item INNER JOIN item INNER JOIN indent_entry " +
                                                    "WHERE iwo_entry.indent_id=indent_item.indent_id AND iwo_item.item_code=indent_item.item_code AND iwo_entry.id=iwo_item.iwo_id AND iwo_item.item_code=item.code AND iwo_entry.indent_id=indent_entry.id and iwo_item.iwo_id="+CmbIwo.getSelectedItem().toString());
                while(reply_items.next()) {
                    int slNo=reply_items.getInt("sl_no");
                    String item=reply_items.getString("name");
                    int qty=reply_items.getInt("quantity");
                    int area=reply_items.getInt("width")*reply_items.getInt("length");
                    String remarks=reply_items.getString("remarks");
                    TblItemsModel.addRow(new Object[]{slNo,item,qty,area,remarks});
                }
                BnOk.setText("Print");
                print=!print;
            }
            else {
                printPrep=new IwoPrintPrep();
                java.text.SimpleDateFormat sd=new java.text.SimpleDateFormat("dd-MM-yyyy");
                printPrep.addEntry(TxtDept.getText(), CmbIwo.getSelectedItem().toString(), sd.format(IwoDate.getDate()), TxtDespatch.getText(), sd.format(DueDate.getDate()));
                String sl,product,qty,area,remarks;
                for(int i=0;i<TblItemsModel.getRowCount();i++) {
                    sl=TblItemsModel.getValueAt(i, 0).toString();
                    product=TblItemsModel.getValueAt(i, 1).toString();
                    qty=TblItemsModel.getValueAt(i, 2).toString();
                    area=TblItemsModel.getValueAt(i, 3).toString();
                    remarks=TblItemsModel.getValueAt(i, 4).toString();
                    printPrep.newItem(sl, product, area, qty, remarks);
                }
                printPrep.writeItems(TxtCustomer.getText());
                printPrep.initPrint();
                this.dispose();
            }
        }catch(java.sql.SQLException ex) {
            javax.swing.JOptionPane.showMessageDialog(this, ex.toString());
        }
    }//GEN-LAST:event_BnOkActionPerformed

    private void BnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_BnCancelActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BnCancel;
    private javax.swing.JButton BnOk;
    private org.jdesktop.swingx.JXComboBox CmbIwo;
    private org.jdesktop.swingx.JXDatePicker DueDate;
    private org.jdesktop.swingx.JXDatePicker IwoDate;
    private javax.swing.JTable TblIwo;
    private javax.swing.JTextArea TxtCustomer;
    private javax.swing.JTextField TxtDept;
    private javax.swing.JTextField TxtDespatch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
    //Manually Declared variables
    org.jdesktop.swingx.autocomplete.AutoCompleteDecorator ac;//To enable autocomplete feature on IWO_NO ComboBox
    javax.swing.DefaultComboBoxModel comboIwo;//Data model that holds iwo ids
    javax.swing.table.DefaultTableModel TblItemsModel;
    boolean print;
    //jdbc...
    java.sql.Connection imConnection;
    java.sql.Statement stmtCmb;
    java.sql.ResultSet replyCmb;
    java.sql.Statement stmt_items;
    java.sql.ResultSet reply_items;
    //Print Preperation Class
    IwoPrintPrep printPrep;
    //End of Declarations

    /**
     * Fetches IWO id's from the database
     * and populates the iwo combobox
     */
    private void initCmbIwo() {
        try {
            stmtCmb=imConnection.createStatement();
            replyCmb=stmtCmb.executeQuery("SELECT iwo_entry.id,iwo_entry.issue_date,iwo_entry.due_date,iwo_entry.recipient,iwo_entry.despatch_mode,customer.name,customer.address " +
                                          "FROM iwo_entry INNER JOIN indent_entry INNER JOIN customer " +
                                          "WHERE iwo_entry.indent_id=indent_entry.id AND indent_entry.customer_code=customer.code");
            while(replyCmb.next()) {
                comboIwo.addElement(replyCmb.getInt("id"));
            }
        }catch(java.sql.SQLException ex) {
            javax.swing.JOptionPane.showMessageDialog(this, ex.toString());
        }
    }

    private void initCmbIwoListener() {
        CmbIwo.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    //Moving cursor to the selected index of the combobox
                    replyCmb.absolute(CmbIwo.getSelectedIndex() + 1);
                    //Populating IWO Info
                    IwoDate.setDate(new java.util.Date(replyCmb.getDate("issue_date").getTime()));
                    DueDate.setDate(new java.util.Date(replyCmb.getDate("due_date").getTime()));
                    TxtDept.setText(replyCmb.getString("recipient"));
                    TxtDespatch.setText(replyCmb.getString("despatch_mode"));
                    TxtCustomer.setText(replyCmb.getString("name")+", "+replyCmb.getString("address"));
                } catch (SQLException ex) {
                    javax.swing.JOptionPane.showMessageDialog(null, ex.toString());
                }

            }
        });
    }
}
